package com.poster.controlleradvice;

import com.poster.enums.ResultCode;
import com.poster.entity.vo.MapResultVo;
import com.poster.exceptions.BusinessException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.ValidationException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.method.MethodValidationException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.resource.NoResourceFoundException;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {


    /**
     * 内部错误处理器
     * @param request 请求体
     * @param e 异常
     * @return 响应体值对象
     */
    @ExceptionHandler(Exception.class)
    MapResultVo exceptionHandler(HttpServletRequest request, Exception e){
        log.error("服务器内部错误，uri {}，引起于", request.getRequestURI(), e);

        return MapResultVo
                .create(ResultCode.SYSTEM_INNER_ERROR)
                .put("errdetail", e.getMessage());
    }

    @ResponseStatus(HttpStatus.NOT_FOUND)
    @ExceptionHandler(NoResourceFoundException.class)
    MapResultVo noResourceFoundExceptionHandler(HttpServletRequest request, NoResourceFoundException e){
        log.error("资源不存在，uri {}，引起于", request.getRequestURI(), e);

        return MapResultVo
                .create(ResultCode.RESULE_DATA_NONE)
                .put("errdetail", e.getMessage());
    }


    @ResponseStatus(HttpStatus.NOT_FOUND)
    @ExceptionHandler(BusinessException.class)
    MapResultVo businessExceptionHandler(HttpServletRequest request, BusinessException e){
        log.error("业务异常，uri {}，引起于", request.getRequestURI(), e);

        return MapResultVo
                .create(e.getCode())
                .put("errdetail", e.getInfo());
    }

    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(MethodArgumentNotValidException.class)
    MapResultVo validationExceptionHandler(HttpServletRequest request, MethodArgumentNotValidException e){
        log.error("业务异常，uri {}，引起于", request.getRequestURI(), e);

        return MapResultVo
                .create(ResultCode.PARAM_IS_INVALID)
                .put("errdetail",ResultCode.PARAM_IS_BLANK.message());
    }



}
